//
//  DDEvaluateViewController.m
//  Dingdong
//
//  Created by 程强 on 16/11/15.
//  Copyright © 2016年 程强. All rights reserved.
//

#import "DDEvaluateViewController.h"
#import "XHStarRateView.h"
#import "TZImagePickerController.h"
#import "DDEvaluateManager.h"
#import "KKTextView.h"
#import "QFMultimedia.h"
#import "KKFileManager.h"
#import "DDEvaluationResultViewController.h"

@interface DDEvaluateViewController ()<TZImagePickerControllerDelegate>
@property (weak, nonatomic) IBOutlet UIView *iconBgView;
@property (weak, nonatomic) IBOutlet UIImageView *goodsIcon;
@property (weak, nonatomic) IBOutlet UIView *scoreBackView;
@property (weak, nonatomic) IBOutlet UIView *desBackView;
@property (weak, nonatomic) IBOutlet KKTextView *desTxt;
@property (weak, nonatomic) IBOutlet UIView *logisticBackView;
@property (weak, nonatomic) IBOutlet UIView *serviceBackView;
@property (weak, nonatomic) IBOutlet UIView *photoBgView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *photoBgViewHeight;
@property (strong, nonatomic) UIButton *cameraButton;
@property (strong, nonatomic) XHStarRateView *goodsStarView;
@property (strong, nonatomic) XHStarRateView *desStarView;
@property (strong, nonatomic) XHStarRateView *logisticStarView;
@property (strong, nonatomic) XHStarRateView *serviceStarView;
@property (strong, nonatomic) DDEvaluateManager *manager;
@property (strong, nonatomic) NSArray *selectedPhotoAry;
@property (assign, nonatomic) NSInteger uploadHandleCount;
@end

@implementation DDEvaluateViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.manager = [DDEvaluateManager new];
    [self layoutEvaluateView];
}
- (void)layoutEvaluateView
{
    self.iconBgView.layer.borderColor = RGBColor(237, 237, 237).CGColor;
    self.iconBgView.layer.borderWidth = 1.0;
    self.desTxt.placeholder = @"Please enter your evaluate...";
    
    [self.goodsIcon sd_setImageWithURL:[NSURL URLWithString:self.goods.thumbnail] placeholderImage:nil];
    
    self.goodsStarView = [[XHStarRateView alloc]initWithFrame:CGRectMake(110, 50, 200, 20) numberOfStars:5 rateStyle:WholeStar isAnination:NO finish:^(CGFloat currentScore) {
        
    }];
    [self.scoreBackView addSubview:_goodsStarView];
    _goodsStarView.currentScore = 5;
    
    self.desStarView = [[XHStarRateView alloc]initWithFrame:CGRectMake(160, 17, ScreenWidth-180, 20) numberOfStars:5 rateStyle:WholeStar isAnination:NO finish:^(CGFloat currentScore) {
        
    }];
    [self.desBackView addSubview:_desStarView];
    _desStarView.currentScore = 5;
    
    self.logisticStarView = [[XHStarRateView alloc]initWithFrame:CGRectMake(160, 17, ScreenWidth-180, 20) numberOfStars:5 rateStyle:WholeStar isAnination:NO finish:^(CGFloat currentScore) {
        
    }];
    [self.logisticBackView addSubview:_logisticStarView];
    _logisticStarView.currentScore = 5;
    
    self.serviceStarView = [[XHStarRateView alloc]initWithFrame:CGRectMake(160, 17, ScreenWidth-180, 20) numberOfStars:5 rateStyle:WholeStar isAnination:NO finish:^(CGFloat currentScore) {
        
    }];
    [self.serviceBackView addSubview:_serviceStarView];
    _serviceStarView.currentScore = 5;
    
    CGFloat width = (ScreenWidth -5*10)/4.0;
    
    self.cameraButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [_cameraButton setFrame:CGRectMake(10, 10, width, width)];
    [_cameraButton setBackgroundImage:LoadImage(@"pingjia_camera") forState:UIControlStateNormal];
    [_cameraButton addTarget:self action:@selector(selectImgClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.photoBgView addSubview:_cameraButton];
    
    self.photoBgViewHeight.constant = width+20;
}
- (IBAction)selectImgClick:(id)sender
{
    TZImagePickerController *vc = [[TZImagePickerController alloc]initWithMaxImagesCount:9 delegate:self];
    [self presentViewController:vc animated:YES completion:nil];
}
- (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingPhotos:(NSArray<UIImage *> *)photos sourceAssets:(NSArray *)assets isSelectOriginalPhoto:(BOOL)isSelectOriginalPhoto infos:(NSArray<NSDictionary *> *)infos
{
    KKLog(@"选择的照片数组%@",photos);
    self.selectedPhotoAry = photos;
    [self showSelectImage:photos];
}
- (void)showSelectImage:(NSArray *)imgAry
{
    for (UIView *view in [self.photoBgView subviews]) {
        if ([view isKindOfClass:[UIImageView class]]) {
            [view removeFromSuperview];
        }
    }
    
    CGFloat width = (ScreenWidth -5*10)/4.0;
    [imgAry enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
       
        UIImage *img = obj;
        UIImageView *imgView = [[UIImageView alloc]initWithImage:img];
        imgView.contentMode = UIViewContentModeScaleAspectFill;
        imgView.clipsToBounds = YES;
        imgView.layer.cornerRadius = 3.0;
        if (idx<=3) {
            [imgView setFrame:CGRectMake(10+(width+10)*idx, 10, width, width)];
        }else if (idx<=7){
            [imgView setFrame:CGRectMake(10+(width+10)*(idx-4), 10+width+10, width, width)];
        }else{
            [imgView setFrame:CGRectMake(10+(width+10)*(idx-8), 10+2*(width+10), width, width)];
        }
        [self.photoBgView addSubview:imgView];
        
        //添加点击放大图
    }];
    
    CGFloat bgHeight = 0;

    CGRect cameraFrame = CGRectZero;
    NSInteger count = imgAry.count;
    NSInteger row = count/4;
    NSInteger colume = count%4;
    if (colume == 0) {
        cameraFrame = CGRectMake(10+(width+10)*0, 10+row*(width+10), width, width);
        bgHeight = 10+(width+10)*(row+1);
    }else{
        cameraFrame = CGRectMake(10+(width+10)*colume, 10+row*(width+10), width, width);
    }
    bgHeight = 10+(width+10)*(row+1);

    [self.cameraButton setFrame:cameraFrame];
    self.photoBgViewHeight.constant =bgHeight;
}

- (void)evaluateGoodsWithPic:(NSString *)picUrl
{
    weak_Self(self);
    [self showMessageHUD:@"Commit..."];
    [[self.manager evaluateGoods:self.goods.goods_id content:self.desTxt.text grade:self.goodsStarView.currentScore store_deliverycredit:self.logisticStarView.currentScore store_desccredit:self.desStarView.currentScore store_servicecredit:self.serviceStarView.currentScore picnames:picUrl]subscribeNext:^(id x) {
        DDEvaluationResultViewController *vc = StoryBoardViewController(@"Evaluate", @"DDEvaluationResultViewController");
        [weakSelf.navigationController pushViewController:vc animated:YES];
    } error:^(NSError *error) {
        NSString *msg = error.userInfo[@"msg"];
        [self showMessageHUD:msg delayHide:1.0];
    } completed:^{
        [weakSelf hideHUD];
    }];
}
- (void)evaluatePicUpload:(UIImage *)img name:(NSString *)name success:(void(^)(NSString *url))sucBlock error:(void(^)())errBlock complete:(void(^)())completeBlock
{
    NSData *imgData = [QFMultimedia compressTo2K:img quality:0.6];
//    UIImage *image = [UIImage imageWithData:imgData];
//    [KKFileManager saveObject:imgData withName:name];
    
    [[self.manager uploadEvaluatePics:imgData picName:name]subscribeNext:^(id x) {
        if (sucBlock) {
            sucBlock(x);
        }
    } error:^(NSError *error) {
        if (errBlock) {
            errBlock();
        }
        NSLog(@"失败的图片名字%@ ",name);
    } completed:^{
        if (completeBlock) {
            completeBlock();
        }
    }];
}
- (IBAction)commitClick:(id)sender
{
    if (_desTxt.text.length == 0) {
        [self showMessageHUD:@"Please enter evaluation" delayHide:1.0];
        return;
    }
    weak_Self(self);
    //上传图片
    self.uploadHandleCount = 0;
    if (self.selectedPhotoAry.count!=0) {
        __block NSMutableArray *urlStrAry = [[NSMutableArray alloc]initWithCapacity:0];
        [self showMessageHUD:@"Upload photos..."];
        [self.selectedPhotoAry enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            UIImage *pic = obj;
            [weakSelf evaluatePicUpload:pic name:FormatString(@"evaluate_%ld.png", idx) success:^(NSString *url) {
                [urlStrAry addObject:url];
            } error:^{
                
            } complete:^{
                weakSelf.uploadHandleCount+=1;
                [weakSelf uploadCompleteTriggerWithUrlAry:urlStrAry];
            }];
        }];
    }else{
        [self uploadCompleteTriggerWithUrlAry:nil];
    }
}
- (void)uploadCompleteTriggerWithUrlAry:(NSArray *)ary
{
    if (self.uploadHandleCount == self.selectedPhotoAry.count) {
        [self hideHUD];
        
        __block NSString *urlStr = @"";
        [ary enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            urlStr =  [urlStr stringByAppendingString:obj];
            if (idx != ary.count-1) {
                urlStr =  [urlStr stringByAppendingString:@";"];
            }
        }];
        
        [self evaluateGoodsWithPic:urlStr];
    }
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
